package msg

import (
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"miners-monitor/models/common"

	"context"
)

type MessageAoModel struct {
	common.BaseModel
	CommonFunc common.CommonFunc
	MessageDb  MessageDbModel
}

func (this *MessageAoModel) FindByStruct(filter Message, opts *options.FindOptions) []Message {
	filterBsonByte, err := this.CommonFunc.BsonMarshal(filter)
	if err != nil {
		panic(err)
	}
	mongoResult := this.MessageDb.Find(filterBsonByte, opts)
	result := []Message{}
	err = mongoResult.All(context.TODO(), &result)
	if err == mongo.ErrNoDocuments {
		return []Message{}
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *MessageAoModel) Find(filter bson.D, opts *options.FindOptions) []Message {
	mongoResult := this.MessageDb.Find(filter, opts)
	result := []Message{}
	err := mongoResult.All(context.TODO(), &result)
	if err == mongo.ErrNoDocuments {
		return []Message{}
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *MessageAoModel) FindOne(filter Message, opts *options.FindOneOptions) Message {
	mongoResult := this.MessageDb.FindOne(filter, opts)
	result := Message{}
	err := mongoResult.Decode(&result)
	if err == mongo.ErrNoDocuments {
		return Message{}
	} else if err != nil {
		panic(err)
	}
	return result
}

func (this *MessageAoModel) Upsert(update Message) {
	this.MessageDb.Upsert(update)
}
